package com.ipzoe.app.core.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ipzoe.app.core.annotation.Login;
import com.ipzoe.app.core.constants.AppConstants;
import com.ipzoe.app.core.exception.AuthException;
import com.ipzoe.app.core.exception.enums.AppExceptionEnum;
import com.ipzoe.common.jwt.JwtTokenUtil;
import com.ipzoe.common.utils.StringUtils;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.mem.service.IMemberService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 * @author zhangmingming
 */
@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {


    @Autowired(required = false)
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IMemberService iMemberService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader(AppConstants.JWT_TOKEN_KEY);
        //如果header中不存在token，则从参数中获取token
        if(StrUtil.isBlank(token)){
            token = request.getParameter(AppConstants.JWT_TOKEN_KEY);
        }

        // 凭证为空
        if (StringUtils.isBlank(token)) {
            throw new AuthException(AppExceptionEnum.TOKEN_IS_NULL);
        }

        log.info("获取到token："+token);

        if (jwtTokenUtil.isTokenExpired(token)) {
            throw new AuthException(AppExceptionEnum.TOKEN_EXPIRED);
        }
        Claims claims = jwtTokenUtil.getClaimFromToken(token);
        if (claims == null) {
            throw new AuthException(AppExceptionEnum.TOKEN_EXPIRED);
        }
        Long memberId = Long.valueOf(jwtTokenUtil.getUserIdFromToken(token));
        String openId = claims.get("openId",String.class);

        if(memberId == null){
            throw new AuthException(AppExceptionEnum.TOKEN_INVALID);
        }
        Member member = iMemberService.getById(memberId);
        if(member == null){
            throw new AuthException(AppExceptionEnum.TOKEN_INVALID);
        }
        if(member.getStatus() == 2){
            throw new AuthException(AppExceptionEnum.TOKEN_FORZEN);
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(AppConstants.REQUEST_ATTRIBUTE_KEY_MEMBER, member);
        if(StrUtil.isNotEmpty(openId)){
            request.setAttribute(AppConstants.REQUEST_ATTRIBUTE_KEY_OPENID, openId);
        }

        return true;
    }
}
